<template>
  <!-- {{ alarmlist }} -->
  <div>
    <div class="searcharea" slot="head">
      <label class="search-item">
        <el-input
          id="search"
          fit
          highlight-current-row
          placeholder="Search"
          prefix-icon="el-icon-search"
          v-model="searchkey"
          @keyup.native="filterAlarm"
          @keyup.enter.native="searchAlarm"
        >
        </el-input>
      </label>
      <el-button
        class="search-item"
        type="primary"
        size="small"
        icon="el-icon-search"
        style="width: 90px"
        >Search
      </el-button>
      <el-button
        class="search-item"
        type="primary"
        size="small"
        icon="el-icon-circle-plus-outline"
        style="width: 70px"
        @click="showAddForm(true)"
        >Add
      </el-button>

      <el-select
        v-model="statusOptionValue"
        clearable
        placeholder="Status"
        style="width: 100px"
        @change="statusSelect"
      >
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        Export
      </el-button>
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-upload2"
        @click="handleImport"
      >
        Import
      </el-button>
    </div>
    <el-table
      slot="down"
      :data="alarmlist"
      height="500px"
      border
      style="width: 100%"
      :row-style="{ height: '20px' }"
    >
      <el-table-column prop="alarmid" label="ID" width="50px">
      </el-table-column>
      <el-table-column prop="name" label="Name"> </el-table-column>

      <el-table-column prop="createBy" label="CreateBy"> </el-table-column>
      <el-table-column
        sortable
        :filters="filterValueList"
        :filter-method="filterHandler"
        prop="gentime"
        label="Create Time"
        width="140"
      >
        <div slot-scope="scope">{{ scope.row.gentime | formatTime }}</div>
      </el-table-column>
      <el-table-column prop="status" label="Status" width="80">
      </el-table-column>
      <el-table-column prop="srouce" label="Srouce" width="80">
      </el-table-column>
      <el-table-column prop="handleby" label="HandleBy" width="100">
      </el-table-column>
      <el-table-column prop="progress" label="Progress"> </el-table-column>
      <el-table-column label="Operation" width="100">
        <template slot-scope="scope">
          <i @click="clickEditRow(scope.row)" class="el-icon-edit"></i>
          <i
            @click="deleteRow(scope.$index, alarmlist)"
            class="el-icon-delete"
          ></i>
        </template>
      </el-table-column>
    </el-table>
    <editForm
      v-if="EditForm_dialog_visible"
      :formVisible="EditForm_dialog_visible"
      @formVisibleEvent="showEditForm"
      :formData="formData"
    >
    </editForm>
    <AddAlarmRecord
      v-if="dialog_visible"
      :dialog_visible="dialog_visible"
      @dialogVisibleEvent="showAddForm"
    ></AddAlarmRecord>
  </div>
</template>

<script>
import { fetchAlarmHis, removeRecord } from "@/api/alarm.js";
// import editForm from "@/components/Alarm/AlarmForm.vue";
import editForm from "@/components/Alarm/EditAlarmRecord.vue";
import AddAlarmRecord from "@/components/Alarm/AddAlarmRecord.vue";
import { parseTime } from "@/utils";

export default {
  name: "AllRisk",
  data() {
    let list = [];
    return {
      dialog_visible: false,
      EditForm_dialog_visible: false,
      statusOptionValue: this.$store.state.statusOptionValue,
      alarmlist: this.$store.state.alarmRecordList,
      alarListForSave: this.$store.state.alarmRecordListSave, // use for alarm filter
      // isAddFormShow: false,
      searchkey: "",
      statusOptions: this.$store.state.statusOptionValue,
      formData: {},
      downloadLoading: false,
    };
  },
  components: {
    AddAlarmRecord,
    editForm,
  },
  created() {
    fetchAlarmHis().then((response) => {
      this.alarmlist = response.data;
      // console.log("this.alarmlist :>> ", this.alarmlist);
      // console.log(" response :>> ", response);
    });
  },
  filters: {
    formatTime(value) {
      let newTime =
        value.substr(0, 4) +
        "/" +
        value.substr(5, 2) +
        "/" +
        value.substr(8, 2) +
        " " +
        value.substr(11, 2) +
        ":" +
        value.substr(14, 2);
      return newTime;
    },
  },
  watch: {
    alarmlist(val) {
      this.$store.state.alarmRecordList = val;
    },
  },
  methods: {
    formatJson(filterVal) {
      return this.alarmlist.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    handleImport() {
      console.log("handleimport ");
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel.js").then((excel) => {
        const tHeader = [
          "AlarmID",
          "Name",
          "CreateTime",
          "Source",
          "Status",
          "Owner",
          "Progress",
          "Record",
        ];
        const filterVal = [
          "alarmid",
          "name",
          "gentime",
          "source",
          "status",
          "handleby",
          "progress",
          "record",
        ];
        const data = this.formatJson(filterVal);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list",
        });
        this.downloadLoading = false;
      });
    },
    formatTimeYMD(timeYMDHMS) {
      let newTime =
        timeYMDHMS.substr(0, 4) +
        "-" +
        timeYMDHMS.substr(5, 2) +
        "-" +
        timeYMDHMS.substr(8, 2);
      return newTime;
    },
    filterHandler(value, row, column) {
      const property = column["property"];
      console.log("row[property] :>> ", row[property]);
      console.log(
        "row[property].indexOf(value) :>> ",
        row[property].indexOf(value)
      );
      if (row[property].indexOf(value) === 0) {
        return row;
      }
    },
    downloadToCSV() {
      let that = this;
      let str = "";
      for (let val in that.alarmlist[0]) {
        str += val + "\t,";
      }
      str += "\n";
      for (let i = 0; i < that.alarmlist.length; i++) {
        for (let item in that.alarmlist[i]) {
          // console.log(typeof that.alarmlist[i][item]);
          // console.log(that.alarmlist[i][item].toString());
          if (that.alarmlist[i][item].toString().indexOf("\n") > 0) {
            console.log(
              "that.alarmlist[i][item] :>> ",
              that.alarmlist[i][item]
            );
          }
          str += `${that.alarmlist[i][item] + "\t"},`;
        }
        str += "\n";
      }
      //encodeURIComponent解决中文乱码
      let uri = "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(str);
      //通过创建a标签实现
      let link = document.createElement("a");
      link.href = uri;
      //对下载的文件命名
      link.download = "downloadList.csv";
      link.text = "download";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    statusSelect(item) {
      console.log("item :>> ", item);
      if (this.alarListForSave.length == 0) {
        //数组复制方法
        this.alarListForSave = this.alarmlist.slice(0);
      } else {
        this.alarmlist = this.alarListForSave.slice(0);
      }
      for (let index = 0; index < this.alarmlist.length; index++) {
        let str = JSON.stringify(this.alarmlist[index].status);
        console.log("str :>> ", str);
        if (str.indexOf(item) === -1) {
          this.alarmlist.splice(index, 1);
          index = index - 1;
        }
      }
    },
    showEditForm(visible) {
      this.EditForm_dialog_visible = visible;
    },
    showAddForm(visible) {
      this.dialog_visible = visible;
      // console.log("dialog_visible :>> ", this.dialog_visible);
    },

    deleteRow(index, rows) {
      // console.log("rows :>> ", rows);
      // console.log("index :>> ", index);
      // console.log("rows[index].alarmid :>> ", rows[index].alarmid);
      let r = confirm("Confirm to remove the record?");
      if (r == true) {
        removeRecord(rows[index].alarmid)
          .then((response) => {
            rows.splice(index, 1);
            // update the alarm list in store
            this.$store.state.alarmRecordListSave = rows;
            this.$store.state.alarmRecordList = rows;
            this.$notify({
              title: "Success",
              message: "Record remove success!",
              type: "success",
              duration: 4,
            });
          })
          .catch((err) => {
            this.$notify.error({
              title: "Error",
              message: "Record remove failed!",
            });
          });
      }
    },
    clickEditRow(row) {
      this.showEditForm(true);
      this.formData = row;
      // console.log("row :>> ", row);
      // console.log("this.formData :>> ", this.formData);
    },
    searchAlarm() {
      console.log("start search alarm");
    },
    filterAlarm() {
      // let this = this;
      if (this.alarListForSave.length == 0) {
        //数组复制方法
        this.alarListForSave = this.alarmlist.slice(0);
      } else {
        this.alarmlist = this.alarListForSave.slice(0);
      }
      for (let index = 0; index < this.alarmlist.length; index++) {
        let str = JSON.stringify(this.alarmlist[index]);
        if (str.indexOf(this.searchkey) === -1) {
          // console.log(str);
          this.alarmlist.splice(index, 1);
          index = index - 1;
        }
      }
    },
  },
  computed: {
    filterValueList() {
      let fl = [];
      let fl_date = [];
      for (let i = 0; i < this.alarmlist.length; i++) {
        let gtime = this.formatTimeYMD(this.alarmlist[i].gentime);
        if (fl_date.indexOf(gtime) === -1) {
          fl_date.push(gtime);
          let str = {
            text: gtime,
            value: gtime,
          };
          fl.push(str);
          //formatTimeYMD
        }
      }

      return fl;
    },
  },
};
</script>

<style>
.searcharea {
  display: flex;
}

.test {
  text-align: center;
}
</style>